package com.lanou3g.ptp.api.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.api.resolver.annotation.SsoStudent;
import com.lanou3g.ptp.api.resolver.annotation.SsoTeacher;
import com.lanou3g.ptp.base.service.BaseService;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.sso.service.SsoService;
import com.lanou3g.ptp.task.service.TaskService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import com.lanou3g.ptp.teachlink.service.TeachlinkService;
import com.lanou3g.ptp.user.service.UserService;
import com.lanou3g.ptp.utils.PtpResult;
import com.lanou3g.ptp.utils.PtpResultUtils;
import com.lanou3g.ptp.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;


@Api(description = "任务接口")
@RestController
@Slf4j
public class TaskController {
    @Reference
    private TaskService taskService;
    @Reference
    private BaseService baseService;
    @Reference
    private TaskStudentService taskStudentService;
    @Reference
    private TeachlinkService teachlinkService;
    @Reference
    private UserService userService;
    @Reference
    private SsoService ssoService;

    @ApiOperation("管理角色通过ID获取任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务Id")
    })
    @GetMapping("/task/{id}")
    public PtpResult taskInfo(@PathVariable Long id) {
        try {
            TaskVO taskVO = taskService.findTaskVOById(id);
            Task task = taskVO.getTask();
            ArrayList<TaskRole> taskRoles = taskVO.getTaskRoles();
            ArrayList<Long> taskStudents = taskVO.getTaskStudents();
            Base base = baseService.findById(task.getBaseId());
            Teachlink teachlink = teachlinkService.findById(task.getTeachlinkId());
            User user = userService.userById(task.getBaseTeacherId());
            Map<String, Object> result = new HashMap<>();
            result.put("id", task.getId());
            result.put("name", task.getName());
            result.put("teachlink_mode", teachlink.getMode());
            result.put("description", task.getDescription());
            result.put("base_name", base.getName());
            result.put("teacher_name", user.getName());
            result.put("teachlink_name", teachlink.getName());
            result.put("longitude", task.getLongitude());
            result.put("latitude", task.getLatitude());
            result.put("distribution", task.getDistribution());
            result.put("task_start_time", task.getTaskStartTime());
            result.put("task_end_time", task.getTaskEndTime());
            result.put("address", base.getAddress());
            result.put("taskStudents", taskStudents);
            result.put("taskRoles", taskRoles);
            return PtpResultUtils.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    /**
     * @param token    token
     * @param taskBody 任务实体
     * @return 结果标识
     * @author 武奇
     */
    @ApiOperation("添加任务")
    @PostMapping("/task")
    public PtpResult newTask(@RequestHeader String token, @RequestBody TaskBody taskBody) {
        try {
            Teacher teacher = (Teacher) this.ssoService.tokenUser(token);
            log.info("开始添加任务: {}, 数据: {}", teacher.getId(), taskBody);
            this.taskService.newTask(teacher.getId(), taskBody);
            return PtpResultUtils.ok();
        } catch (IllegalArgumentException e) {
            return PtpResultUtils.error(400, e.getMessage());
        }

    }

    @ApiOperation("管理角色删除一任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务Id")
    })
    @DeleteMapping("/task/{id}")
    public PtpResult delete(@PathVariable Long id) {
        try {
            taskService.delete(id);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    /**
     * @param page 分页数据, page & size
     * @return 结果标识
     * @author 武奇
     * @date 2019-07-30 20:46:55
     */
    /*
    当前登录teacherId
    -> 类型是分散的所有教学环节
    -> 状态是学生自主提交的任务
     */
    @ApiOperation("查询所有学生自主提交的实习任务")
    @GetMapping("/tasks")
    public PtpResult findStuSubmitTasks(@SsoTeacher Teacher teacher, Pageable page) {
//        Teacher teacher = (Teacher) this.ssoService.tokenUser(token);
        PageInfo<TaskResult> pi = this.taskService.findStuSubmitTasks(teacher.getId(), page);
        return PtpResultUtils.ok(pi);
    }

    @ApiOperation("Post方式查询所有学生自主提交的实习任务")
    @PostMapping("/tasks")
    public PtpResult findStuSubmitTasksPost(@SsoTeacher Teacher teacher, @RequestBody Pageable page) {
        return this.findStuSubmitTasks(teacher, page);
    }

    /**
     * @param token  token
     * @param taskId 任务id
     * @return 操作结果标识
     * @author 武奇
     * @date 2019-07-31 18:52:03
     */
    @ApiOperation("老师审批实习任务-通过")
    @PostMapping("/task/pass/{taskId}")
    public PtpResult passTask(@RequestHeader String token, @PathVariable Long taskId) {
        Teacher teacher = (Teacher) this.ssoService.tokenUser(token);
        Long teacherId = teacher.getId();
        boolean success = this.taskService.passTask(teacherId, taskId);
        return success ? PtpResultUtils.ok() : PtpResultUtils.error(401, "您没有修改的权限");
    }

    /**
     * @param token  token
     * @param taskId 任务id
     * @return 操作结果标识
     * @author 武奇
     * @date 2019-07-31 19:21:32
     */
    @ApiOperation("老师审批实习任务-拒绝")
    @PostMapping("/task/denied/{taskId}")
    public PtpResult denyTask(@RequestHeader String token, @PathVariable Long taskId) {
        Teacher teacher = (Teacher) this.ssoService.tokenUser(token);
        Long teacherId = teacher.getId();
        boolean success = this.taskService.denyTask(teacherId, taskId);
        return success ? PtpResultUtils.ok() : PtpResultUtils.error(401, "您没有修改的权限");
    }

    @ApiOperation("管理角色批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "任务id数组")
    })
    @DeleteMapping("/tasks")
    public PtpResult deletes(@RequestBody Long[] ids) {
        try {
            taskService.deletes(ids);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    /**
     * @param task
     * @return
     * @author wuqi
     * @date 2019-09-03 09:55:18
     */
    @ApiOperation("管理角色修改")
    @PutMapping("/task")
    public PtpResult update(@RequestBody TaskBody task) {
        this.taskService.updateTask(task);
        return PtpResultUtils.ok("任务修改成功");
    }

    @GetMapping("/teachlink/{teachlinkId}/task")
    public PtpResult getTaskInfo(@PathVariable Long teachlinkId) {
        TaskBody task = this.taskService.findTaskBodyByTeachlink(teachlinkId);
        return PtpResultUtils.ok(task);
    }

    /**
     * 查询分散的某个教学环节下的所有任务概况
     *
     * @param teachlinkId 教学环节id
     * @return 查询分散的某个教学环节下的所有任务概况
     * @author 武奇
     * @date 2019-08-05 20:41:38
     */
    @ApiOperation("查询分散的某个教学环节下的所有任务概况")
    @PostMapping("/teachlink/{teachlinkId}/tasks/divert")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teachlinkId", value = "教学环节的id")
    })
    public PtpResult view(@PathVariable Long teachlinkId, @RequestBody(required = false) Pageable page) {
        PageInfo<SimpleTask> pi = taskService.findDivertTasksByTeachlinkId(teachlinkId, page);
        return PtpResultUtils.ok(pi);
    }


    /**
     * 查询集中模式的教学环节下的任务详情
     *
     * @param teachlinkId 集中模式的教学环节id
     * @return 查询结果信息
     */
    @ApiOperation("某个集中模式的教学环节下的任务详情")
    @GetMapping("/teachlink/{teachlinkId}/task/central")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teachlinkId", value = "教学环节的id")
    })
    public PtpResult centralTaskDetails(@PathVariable Long teachlinkId) {
        CentralTaskResult result = this.taskService.findCentralTaskByTeachlinkId(teachlinkId);
        return PtpResultUtils.ok(result);
    }


    @ApiOperation("管理员批量修改成合格任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskIds", value = "任务id的数组")
    })
    @PutMapping("/updatesYes/{taskIds}")
    public PtpResult updatesYes(@PathVariable Long[] taskIds, Task task) {
        try {
            task.setStatus(0);
            taskService.updates(taskIds, task);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("管理员批量修改成不合格任务")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "taskIds", value = "任务id数组", paramType = "Integer")
    })
    @PutMapping("/updatesNo/{taskIds}")
    public PtpResult updatesNo(@PathVariable Long[] taskIds, Task task) {
        try {
            task.setStatus(4);
            taskService.updates(taskIds, task);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("学生增加任务")
    @PostMapping("/myTask")
    public PtpResult studentInsert(@RequestBody TaskVO taskVO, String token) {
        try {
            taskService.insert1(taskVO, token);
            return PtpResultUtils.ok(200);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("学生修改任务")
    @PutMapping("/myTask/{id}")
    public PtpResult studentUpdate(@PathVariable Long id, TaskVO taskVO, String token) {
        try {
            this.taskService.update(id, taskVO, token);
            return PtpResultUtils.ok(200);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("学生查看自己所有的任务（0未开始 1进行中 2任务结束 3学生自主提交 4老师审批不合格）以及可自主添加任务的教学环节")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户码", required = true, paramType = "header")
    })
    @GetMapping("/myTasks")
    public PtpResult studentFind(@ApiIgnore @SsoStudent Student student) {
        try {
            List<Task> tasks = taskService.findByStudentId(student.getId());
            List<Teachlink> teachlinks = teachlinkService.findByClazzId(student.getClazzId());
            if (teachlinks.size() > 0) {
                Iterator<Teachlink> iterator = teachlinks.iterator();
                while (iterator.hasNext()) {
                    Teachlink teachlink = iterator.next();
                    for (Task task : tasks) {
                        if (task.getTeachlinkId().equals(teachlink.getId())) {
                            iterator.remove();
                            break;
                        }
                    }
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("tasks", tasks);
            if (teachlinks.size() > 0) {
                result.put("teachlink", teachlinks);
            }
            return PtpResultUtils.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("学生查看任务明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id")
    })
    @GetMapping("/myTask/{taskId}")
    public PtpResult studentFind(@PathVariable Long taskId) {
        try {
            Task task = taskService.findTaskDescById(taskId);
            if (task != null) {
                return PtpResultUtils.ok(task);
            } else {
                return PtpResultUtils.error(404, "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("日志情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id")
    })
    @GetMapping("/diarySituation/{taskId}")
    public PtpResult diarySituation(@PathVariable Long taskId) {
        try {
            Map<String, List<Diary>> dateListMap = taskService.diarySituation(taskId);
            return PtpResultUtils.ok(dateListMap);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("查询当前学生的所有任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户码", required = true, paramType = "header")
    })
    @GetMapping("/showTask")
    public PtpResult showTask(@ApiIgnore @SsoStudent Student student) {
        try {
            List<Task> tasks = taskService.showByStudentId(student.getId());
            if (tasks.size() != 0) {
                return PtpResultUtils.ok(tasks);
            } else {
                return PtpResultUtils.error(404, "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }

    @ApiOperation("学生自主报名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户码", required = true, paramType = "header"),
            @ApiImplicitParam(name = "id", value = "任务ID")
    })
    @GetMapping("/task/apply/{id}")
    public PtpResult studentApply(@ApiIgnore @SsoStudent Student student, @PathVariable long id
    ) {

        Boolean boor = taskStudentService.taskApply(student, id);

        return boor ? PtpResultUtils.ok() : PtpResultUtils.error(499, "报名时间以过或已完成报名");
    }


    @ApiOperation("查询当前实习单位的所有任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户码", required = true, paramType = "header")
    })
    @GetMapping("/baseTasks")
    public PtpResult tasksByBase(@ApiIgnore @SsoTeacher Teacher teacher) {
        try {
            List<Task> tasks = taskService.findByBaseId(teacher.getBaseId());
            if (tasks.size() != 0) {
                return PtpResultUtils.ok(tasks);
            } else {
                return PtpResultUtils.error(404, "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }
    }
}

